/*******************************************************************************
 * Package: com.song.boot.springstudy.nio
 * Type:    Server
 * Date:    2022-09-03 21:53
 *
 * Copyright (c) 2022 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.boot.springstudy.nio;

import lombok.SneakyThrows;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * 功能描述： 服务端
 *
 * @author Songxianyang
 * @date 2022-09-03 21:53
 */
public class Server {
    @SneakyThrows
    public static void main(String[] args) {
        // 获取serverSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        
        // 获取 selector
        Selector selector = Selector.open();
        // 设置非阻塞
        serverSocketChannel.configureBlocking(false);
        
        // 设置端口
        serverSocketChannel.bind(new InetSocketAddress(9999));
        // 把serverSocketChannel 注册到selector
        // OP_ACCEPT 客户端连接
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        
        // 不停的监听事件
        while (true) {
            //获取选择器中的 连接事件(如果1s没有连接就打印下面语句）
            if (selector.select(1000) <= 0) {
                System.out.println("如果1s没有连接就打印下面语句");
            }
            // 获取选择器中的真是事件
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> keysIterator = keys.iterator();
            // 去找到具体的事件
            while (keysIterator.hasNext()) {
                SelectionKey key = keysIterator.next();
                // 获取客户端连接事件
                if (key.isAcceptable()) {
                    // 获取客户端 socketChannel
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    // 客户端socketChannel 设置非阻塞
                    socketChannel.configureBlocking(false);
                    // 客户端socketChannel 注册到 select上(从通道里面读取数据）
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                // 判断我要从key中读到具体的事件（读）
                if (key.isReadable()) {
                    // 获取SelectionKey中的读Channel
                    SocketChannel socketChannel = (SocketChannel) key.channel();
                    // 获取byteBuffer
                    ByteBuffer byteBuffer =(ByteBuffer) key.attachment();
                    socketChannel.read(byteBuffer);
                    System.out.println(new String(byteBuffer.array()));
                }
                keysIterator.remove();
            }
        }
        
    }
}
